@file:JvmName("SegmentHelper")

package com.hwy.widget.segment

import android.graphics.Color
import android.graphics.Path
import androidx.annotation.ColorInt
import androidx.annotation.FloatRange

/**
 * =======================================
 * 作者: hewenyu
 * 日期: 2022/5/4 12:27
 * 说明: Segment辅助类
 * =======================================
 */

/**
 * 根据百分比计算两个颜色的中间值
 *
 * @param fromColor 开始的color值
 * @param toColor 最终的color值
 * @param fraction 比例，取值为[0,1]，为0时返回 fromColor， 为1时返回 toColor
 * @return 返回计算的颜色值
 */
@ColorInt
fun calculateColor(
    @ColorInt fromColor: Int,
    @ColorInt toColor: Int,
    @FloatRange(from = 0.0, to = 1.0) fraction: Float
): Int {
    val minColorA = Color.alpha(fromColor)
    val maxColorA = Color.alpha(toColor)
    val resultA = ((maxColorA - minColorA) * fraction + minColorA).toInt()

    val minColorR = Color.red(fromColor)
    val maxColorR = Color.red(toColor)
    val resultR = ((maxColorR - minColorR) * fraction + minColorR).toInt()

    val minColorG = Color.green(fromColor)
    val maxColorG = Color.green(toColor)
    val resultG = ((maxColorG - minColorG) * fraction + minColorG).toInt()

    val minColorB = Color.blue(fromColor)
    val maxColorB = Color.blue(toColor)
    val resultB = ((maxColorB - minColorB) * fraction + minColorB).toInt()

    return Color.argb(resultA, resultR, resultG, resultB)
}

/**
 * 计算圆角path
 *
 * @param width     控件宽度
 * @param height    控件高度
 * @param corner    控件圆角半径
 * @param path      保存路径
 */
fun calculateCornerPath(width: Float, height: Float, corner: Float, path: Path) {
    if (corner <= 0) {
        return
    }

    // 每个圆角转过的角度
    val sweepAngle = 90F
    // 直径
    val diameter = corner * 2F
    path.run {
        reset()
        moveTo(0F, corner)
        arcTo(0F, 0F, diameter, diameter, 180F, sweepAngle, false)
        lineTo(width - corner, 0F)
        arcTo(width - diameter, 0F, width, diameter, 270F, sweepAngle, false)
        lineTo(width, height - corner)
        arcTo(width - diameter, height - diameter, width, height, 0F, sweepAngle, false)
        lineTo(corner, height)
        arcTo(0F, height - diameter, diameter, height, 90F, sweepAngle, false)
    }
}